package com.xtaller.easy.admin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xtaller.common.convert.*;
import com.xtaller.easy.admin.base.TServiceImpl;
import com.xtaller.easy.admin.mapper.BaseUserMapper;
import com.xtaller.easy.admin.model.BaseUser;
import com.xtaller.easy.admin.model.BaseUserRole;
import com.xtaller.easy.admin.service.IBaseUserService;
import com.xtaller.easy.admin.specification.RoleSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import com.xtaller.common.bean.Where;
import org.springframework.transaction.annotation.Transactional;

/**
* Created by Taller on 2018/04/13
*/
@Service
public class BaseUserService extends TServiceImpl<BaseUserMapper,BaseUser> implements IBaseUserService {
   @Autowired
   private SysLabelService labelService;
   @Autowired
   private BaseUserRoleService roleService;
    /**************************CURD begin******************************/
   // 创建
   @Override
   public BaseUser createBaseUser(BaseUser model) {
       if(this.insert(model))
           return this.selectById(model.getId());
       return null;
   }
 
   // 删除
   @Override
   public Boolean deleteBaseUser(Object ids,String reviser) {
       return this.delete(ids,reviser);
   }
 
   // 修改
   @Override
   public BaseUser updateBaseUser(BaseUser model) {
       if(this.update(model))
           return this.selectById(model.getId());
       return null;
   }
 
   // 查询
   @Override
   public List<BaseUser> findByIds(Object ids) {
       return this.selectByIds(ids);
   }
 
   // 属于
   @Override
   public Boolean exist(List<Where> w) {
       w.add(new Where("1"));
       return this.query(w).size() > 0;
   }
 
   // 查询一个id是否存在
   @Override
   public Boolean existId(Object id) {
       where = W.f(
               W.and("id","eq",id),
               W.field("1")
       );
       return this.query(where).size() > 0;
   }



    /**************************CURD end********************************/
    @Override
    public JSONObject getPageList(int index, int pageSize, String where) {
        JSONObject result = new JSONObject();
        result.put("rows", new ArrayList<>());
        // 总记录数
        JSONObject row = baseMapper.getPageCount(where);
        int totalCount = row.getInteger("total");
        result.put("total", totalCount);
        if(totalCount == 0)
            return result;
        // 分页数据
        index = index < 0 ? 1:index;
        int limit = (index - 1) * pageSize;
        result.put("rows", formatLabel(F.f2l(baseMapper.getPage(where, limit, pageSize), "id")));
        return result;
    }

    @Override
    public List<JSONObject> getUserLabel(String userId, List<JSONObject> data) {
        List<JSONObject> labels = J.o2l(labelService.getLabelByCode("user").get("children"));
        for(JSONObject label:labels){
            List<JSONObject> childrens = J.o2l(label.get("children"));
            if(childrens.size() > 0){
                for(JSONObject children:childrens){
                    if(data.size() > 0){
                        for(JSONObject item:data){
                            if(V.isEqual(item.getString("userId"), userId) &&
                                    V.isEqual(item.getString("labelId"), children.getString("id"))){
                                children.put("val", item.getString("val"));
                                children.put("txt", item.getString("val"));
                                if(children.getInteger("type") == 9){
                                    List<JSONObject> options = J.o2l(children.get("options"));
                                    if(options.size() > 0){
                                        for(JSONObject option:options){
                                            if(option.getString("val").equals(item.getString("val"))){
                                                children.put("txt", option.getString("txt"));
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }else {
                        children.put("val", "");
                    }
                }
            }
            label.put("children", childrens);
        }
        return labels;
    }

    @Override
    public List<JSONObject> getRoleByCode(JSONObject where) {
        return F.f2l(baseMapper.getRoleByCode(where),
                "userId", "roleId");
    }

    @Transactional
    @Override
    public Boolean configUserRoel(RoleSet object) {
        // 初始化数据
        baseMapper.initUserRole(object.getUserId());
        String[] roleIds = object.getRoleIds();
        if(roleIds.length > 0){
            for(String roleId:roleIds){
                BaseUserRole role = new BaseUserRole();
                role.setUserId(object.getUserId());
                role.setRoleId(roleId);
                roleService.createModel(role);
            }
        }
        return true;
    }

    @Override
    public JSONObject getAuthByRoleIds(JSONObject object) {
        List<JSONObject> auths = F.f2l(baseMapper.getAuthByRoleIds(object),
                "roleId", "id", "menuId", "authId", "parentId");
        List<JSONObject> menus = new ArrayList<>();
        List<JSONObject> buttons = new ArrayList<>();
        // 取出菜单数据 取出按钮数据
        for(JSONObject auth:auths){
            if(auth.getInteger("isMenu") == 1){
                JSONObject m = new JSONObject();
                m.put("id", auth.getString("id"));
                m.put("name", auth.get("name"));
                m.put("text", auth.get("name"));
                m.put("parentId", auth.getString("parentId"));
                m.put("icon", auth.get("icon"));
                m.put("url", auth.get("url"));
                m.put("api", auth.get("api"));
                m.put("sort", auth.get("sort"));
                m.put("isHidden", auth.get("isHidden"));
                m.put("btns", new ArrayList<>());
                menus.add(m);
            }else{
                JSONObject b = new JSONObject();
                b.put("isBtn", auth.get("isBtn"));
                b.put("id", auth.getString("authId"));
                b.put("menuId", auth.getString("id"));
                b.put("name", auth.get("btnName"));
                b.put("fun", auth.get("fun"));
                b.put("icon", auth.get("btnIcon"));
                b.put("buttonId", auth.getString("authId"));
                b.put("api", auth.get("btnApi"));
                b.put("method", auth.get("method"));
                b.put("sort", auth.get("btnSort"));
                buttons.add(b);
            }
        }

        // 菜单整合按钮
        if(menus.size() > 0 && buttons.size() > 0){
            for(JSONObject menu:menus){
                List<JSONObject> btns = new ArrayList<>();
                for(JSONObject button:buttons){
                    if(V.isEqual(menu.getString("id"), button.getString("menuId"))){
                        btns.add(button);
                    }
                }
                menu.put("btns", btns);
            }
        }
        JSONObject result = new JSONObject();
        result.put("menus", menus);
        result.put("btns", buttons);
        return result;
    }

    @Override
    public List<JSONObject> getLabelByUserIds(String userIds) {
        return F.f2l(baseMapper.getRoleByUserIds(userIds),
                "userId", "roleId");
    }

    public List<JSONObject> formatLabel(List<JSONObject> list){
        String userIds = L.getAttrs(list, "id");
        // 读取标签数据
        List<JSONObject> labels = getLabelByUserIds(userIds);
        // 读取角色数据
        List<JSONObject> roles = F.f2l(baseMapper.getRoleByUserIds(userIds),
                "userId", "roleId");
        for(JSONObject object:list){
            object.put("label", getUserLabel(object.getString("id"), labels));
            object.put("role", formatRole(object.getString("id"), roles));
        }
        return list;
    }

    private String[] formatRole(String userId, List<JSONObject> list){
        List<JSONObject> item = new ArrayList<>();
        if(list.size() > 0){
            for(JSONObject role:list){
                if(V.isEqual(role.getString("userId"), userId)){
                    item.add(role);
                }
            }
        }
        int len = item.size();
        if(len > 0){
            String[] tem = new String[len];
            for(int i=0;i<len;i++){
                tem[i] = item.get(i).getString("roleId");
            }
            return tem;
        }else {
            return new String[0];
        }
    }
}